package com.santiao.youxiang.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.santiao.youxiang.bean.YibaoBean

//import com.santiao.youxiang.databinding.FragmentMainBinding
import com.santiao.youxiang.event.XXLEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.getValue
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.allen.library.shape.ShapeTextView
import com.santiao.publics.ui.SettingFragment
import com.santiao.publics.util.SharedPreferencesUtil
import com.santiao.publics.util.SharedPreferencesUtil.getFirstHabit
import com.santiao.publics.util.SharedPreferencesUtil.setFirstHabit
import com.santiao.youxiang.ext.thrillClickListener

import com.santiao.youxiang.R
import com.santiao.youxiang.database.Detail

import com.santiao.youxiang.database.habitBill
import com.santiao.youxiang.database.habitBill.Weekly
import com.santiao.youxiang.database.habitTimeLine
//import com.santiao.youxiang.database.habitTimeLine.Detail
import com.santiao.youxiang.databinding.FragmentHabitBinding
//import com.santiao.youxiang.database.Bill

import com.santiao.youxiang.ui.activity.HabitEditActivity
import com.santiao.youxiang.ui.activity.TimeLineActivity
import com.santiao.youxiang.ui.adapter.HabitAdapter
import org.litepal.LitePal
import java.time.LocalDateTime

//import com.santiao.youxiang.databinding.FramentShebaoBillBinding


class HabitFragment : Fragment(){

    var binding : FragmentHabitBinding?=null

    var groupedByMonth: Map<String, List<YibaoBean>>?=null

    var weekList :ArrayList<Weekly?>?=null

    var detList :ArrayList<Detail?>?=null

    private val HviewModel: HomeViewModel by viewModels()

    private lateinit var Hadapter: HabitAdapter



    private lateinit var water_container: FrameLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHabitBinding.inflate(inflater, container, false)
        return binding!!.root
    }

    @SuppressLint("NewApi")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView(view)

        initdata()
        initRv()
        initClick()

    }
    private fun initView(view: View){
        weekList=ArrayList()
if (getFirstHabit()==0L){
    firstSet()
}

    }

    @SuppressLint("NewApi")
    fun firstSet(){
        Log.e( "firstSet: ", "1")
        weekList!!.clear()
        var week =Weekly()
        week!!.sate="1"
        for (i in 1..7) {
            weekList!!.add(i-1,week)
        }

        val current = LocalDateTime.now()

        val year = current.year
        val monthValue = current.monthValue
        val dayOfMonth = current.dayOfMonth

        val hour = current.hour
        val minute = current.minute
        val second = current.second

        var updateTime="$year-$monthValue-$dayOfMonth $hour:$minute:$second"

        var habitob= habitBill(habitName = "早起",habitToday_target="1",
            habitTargetDay="30",habitRemind="1",
            RemindTime="7"+":"+"00",habitWeekly=weekList,imageType="3",update=updateTime)


        var habitob2= habitBill(habitName = "阅读",habitToday_target="1",
            habitTargetDay="30",habitRemind="1",
            RemindTime="20"+":"+"00",habitWeekly=weekList,imageType="1",update=updateTime)

        var habitob3= habitBill(habitName = "运动",habitToday_target="1",
            habitTargetDay="21",habitRemind="0",
            RemindTime="16"+":"+"24",habitWeekly=weekList,imageType="0",update=updateTime)

        var habitob4= habitBill(habitName = "喝水",habitToday_target="8",
            habitTargetDay="30",habitRemind="0",
            RemindTime="16"+":"+"26",habitWeekly=weekList,imageType="4",update=updateTime)

        try {
            habitob.save()
            habitob2.save()
            habitob3.save()
            habitob4.save()
        }catch (e: Exception){
            Log.e( "firstSet: ", e.toString())
        }



        setFirstHabit(1L)

    }


    @RequiresApi(Build.VERSION_CODES.O)
    override fun onResume() {
        super.onResume()
        initdata()
    }

    fun initRv(){


        Hadapter=HabitAdapter()


        val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvHabit?.layoutManager = layoutManager
        binding!!.rvHabit?.adapter = Hadapter

//        Hadapter!!.setOnItemClickListener { adapter, view, position ->
//
//            Log.e("initRv: ","1" )
//
//            var hab = LitePal.where("id = ?", Hadapter.data[position].id.toString()).findFirst(habitBill::class.java)
//
//            checkInDialog(hab)
//
//            Log.e("initRv: ",hab.toString() )
//
//
//        }

//        Hadapter.onItemClickListener = object : HabitAdapter.OnItemClickListener {
//            override fun onItemClick(data: habitBillBean) {
//                // 处理点击事件
//
//                Log.e("initRv: ","1" )
//
//                var hab = LitePal.where("id = ?", data.id.toString()).findFirst(habitBill::class.java)
//
//                checkInDialog(hab)
//
//                Log.e("initRv: ",hab.toString() )
//
//            }
//        }

        Hadapter!!.setOnItemChildClickListener { _, view, position ->



            if (view.id == R.id.ll_del) {
                // 删除逻辑
                delFromdb(Hadapter!!.data.get(position).id.toString())
                Hadapter!!.removeAt(position)
                Hadapter!!.notifyItemRemoved(position)

            }

            if (view.id == R.id.ll_edit) {
                // 编辑逻辑
//                delFromdb(billadapter!!.data.get(position).id.toString())
//                billadapter!!.removeAt(position)
//                billadapter!!.notifyItemRemoved(position)
                HabitEditActivity.startActivity(requireContext(),"2",Hadapter!!.data.get(position).id.toString())

            }

            if (view.id == R.id.ll_main) { //主页面

                Log.e("initRv: ","1" )

                var hab = LitePal.where("id = ?", Hadapter.data[position].id.toString()).findFirst(habitBill::class.java)

                checkInDialog(hab)

                Log.e("initRv: ",hab.toString() )

            }

//            val bundle=Bundle()
//            bundle.putInt("type", type)
//            bundle.putSerializable("email", itemData)
//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)

        }


    }

    fun delFromdb(uid : String){

        var hab = LitePal.where("id = ?", uid).findFirst(habitBill::class.java)

        // 查询
        val result = LitePal.where("habitid = ?", uid).find(Detail::class.java)

//        LitePal.deleteAll(Detail::class.java, "timelineId = ?", result[?].id)

//       var lineres= LitePal.where("timelineId = ?", id.toString())
//            .find(Detail::class.java)

// 处理查询结果：删除关联的 habitTimeLine 数据
        if (result != null /*&& result.isNotEmpty()*/) {



            LitePal.deleteAll(Detail::class.java, "habitid = ?", uid)

//            LitePal.deleteAll(habitTimeLine::class.java, "habitTimeId = ?", uid)
            Log.e("delete_associated", "Deleted associated habitTimeLine records")
        }


        hab.delete()

    }

    @SuppressLint("NewApi")
    fun save_timeline(habit:habitBill,des: String){

        val current = LocalDateTime.now()

        val year = current.year
        val monthValue = current.monthValue
        val dayOfMonth = current.dayOfMonth

        val hour = current.hour
        val minute = current.minute
        val second = current.second

        var updateTime="$year-$monthValue-$dayOfMonth $hour:$minute:$second"

        var comob="$year-$monthValue-$dayOfMonth"
        var linedate="$hour:$minute:$second"

//        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
//
//// 将当前时间格式化为字符串
//        val formattedCurrent = current.format(formatter)



        if (habit.checkIns!!.toInt()+1>=habit.habitToday_target!!.toInt()&&habit.todayFnish=="0"){
            habit.habithold_day=(habit.habithold_day!!.toInt()+1).toString()
            habit.todayFnish="1"
        }

        habit.update=updateTime
        habit.checkIns= (habit.checkIns!!.toInt()+1).toString()


        habit.save()

        val current2 = LocalDateTime.now()

// 格式化当前日期为 yyyy-MM-dd
        val formattedDate = current2.toLocalDate().toString()

        Log.e( "save_timeline:匹配时间 ", comob+"%")

// 查询数据库中与当前日期相同的记录
        val result = LitePal.where("date LIKE ?", comob+"%").findFirst(habitTimeLine::class.java)

//        var det=Detail(habitName=habit.habitName,habit.imageType,formattedDate,des)
//        Log.e("save_timeline:result ", result.toString())
// 处理查询结果
        if (result != null) {

            val det = Detail().apply {
                habitName = habit.habitName
                habitType = habit.imageType?.toString()
                dateTime = linedate
                describe = des
                timelineId = result.id // 设置关联
                habitid=habit.id
            }


//            if (result.detail == null) {
//                result.detail = ArrayList()
//            }
//
//            // 添加新的 Detail 对象
//            result.detail!!.add(det)

            if (det.save())   {
                Log.e( "save_timeline: ", "旧数据保存成功")
                Log.e("save_timeline:result ", result.toString())
                try {
                    checkInDialogAfter(habit)
                }catch (e: Exception){
                    Log.e( "save_timeline: ", e.toString())
                }

            }else{
                Log.e( "save_timeline: ", "保存失败")
            }
            
        } else {
//            detList=ArrayList<Detail?>()
//            detList!!.add(det)
            var timelineob= habitTimeLine(date = updateTime,habitTimeId=habit.id/*,detail=detList*/)

         if (timelineob.save())   {

             val dets = Detail().apply {
                 habitName = habit.habitName
                 habitType = habit.imageType?.toString()
                 dateTime = linedate
                 describe = des
                 timelineId = timelineob.id // 设置关联
                 habitid=habit.id
             }

             if (dets.save()){
                 checkInDialogAfter(habit)
                 Log.e( "save_timeline: ", "今天打卡保存成功")
             }


         }else{
             Log.e( "save_timeline: ", "保存失败")
         }

        }

        

    }

    private fun checkInDialog(habit:habitBill) {
        val dialog = Dialog(requireContext(), R.style.MyDialog)
//        dialog.setCancelable(false)
//        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_habit1);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )


        dialog.window?.setGravity(Gravity.CENTER);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_name)
        var tvtime=dialog.findViewById<TextView>(R.id.tv_time)
        var tvnum=dialog.findViewById<TextView>(R.id.tv_num)
        var tvtimes=dialog.findViewById<TextView>(R.id.tv_times)
        var tv_today_ob=dialog.findViewById<TextView>(R.id.tv_per_day)
        var etdes=dialog.findViewById<EditText>(R.id.et_des)
        var close=dialog.findViewById<ShapeTextView>(R.id.tv_close)
        var checkin=dialog.findViewById<ShapeTextView>(R.id.tv_check)
        var photo=dialog.findViewById<ImageView>(R.id.iv_photo)
        
        
        tvtitle.text=habit.habitName
        tvtime.text=habit.update
        tvtimes.text=habit.checkIns
        tv_today_ob.text=   "/${habit.habitToday_target}次"

        when (habit.imageType){
            "1"->{
             
                photo.setImageResource(R.drawable.ic_habit_bg5)
            }

            "2"->{
                photo.setImageResource(R.drawable.ic_habit_bg6)
            }

            "3"->{
                photo.setImageResource(R.drawable.ic_habit_bg7)
            }

            "4"->{
                photo.setImageResource(R.drawable.ic_habit_bg8)
            }
            else -> {
                photo.setImageResource(R.drawable.ic_habit_bg9)
            }

        }

        // 监听文本变化
        etdes.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化之前触发
            }

            override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {
                // 在文本变化时触发
                // 这里可以获取到文本的变化，例如：
//                val inputText = charSequence.toString()
//                println("输入的文本: $inputText")
                tvnum.text=charSequence!!.length.toString()
            }

            override fun afterTextChanged(editable: Editable?) {
                // 在文本变化之后触发
            }
        })

        close.thrillClickListener {
            dialog.cancel()
        }

        checkin.thrillClickListener {
            save_timeline(habit,etdes.text.toString().trim())
            if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD)   ) {
                SettingFragment.adLoad3(0, null, null, context, activity);

                Handler().postDelayed({ dialog.dismiss() }, 1200)
            }else {

                dialog.dismiss()
            }
//            checkInDialogAfter(habit)
        }

        dialog.show()

//        dialog.findViewById<TextView>(R.id.tv_name).setOnClickListener {
//            firstShowDialogTwo(dialog)
//        }
    }


    private fun checkInDialogAfter(habit:habitBill) {
        val dialog = Dialog(requireContext(), R.style.MyDialog)
//        dialog.setCancelable(false)
//        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_habit2);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        //底部弹出的Dialog
        dialog.window?.setGravity(Gravity.CENTER);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_name)
        var tvtime=dialog.findViewById<TextView>(R.id.tv_time)
        var tvnum=dialog.findViewById<TextView>(R.id.tv_num)
        var tvtoday_times=dialog.findViewById<TextView>(R.id.tv_times)
        var tv_today_ob=dialog.findViewById<TextView>(R.id.tv_per_day)
//        var etdes=dialog.findViewById<EditText>(R.id.et_des)
        var close=dialog.findViewById<ShapeTextView>(R.id.tv_close)
//        var checkin=dialog.findViewById<ShapeTextView>(R.id.tv_check)
        var photo=dialog.findViewById<ImageView>(R.id.iv_photo)

        tvtitle.text=habit.habitName
        tvtime.text=habit.update
        tvtoday_times.text=habit.checkIns
        tv_today_ob.text="/${habit.habitToday_target}次"
        tvnum.text=habit.habithold_day

        when (habit.imageType){
            "1"->{

                photo.setImageResource(R.drawable.ic_habit_bg5)
            }

            "2"->{
                photo.setImageResource(R.drawable.ic_habit_bg6)
            }

            "3"->{
                photo.setImageResource(R.drawable.ic_habit_bg7)
            }

            "4"->{
                photo.setImageResource(R.drawable.ic_habit_bg8)
            }
            else -> {
                photo.setImageResource(R.drawable.ic_habit_bg9)
            }

        }

        close.thrillClickListener {
            dialog.cancel()
        }

        dialog.show()

        initdata()

//        checkin.thrillClickListener {
//            dialog.cancel()
//        }


    }




    fun initClick(){

        binding!!.llHabitAdd.thrillClickListener {
            HabitEditActivity.startActivity(requireContext(),"1","0")

        }

        binding!!.llHabitTime.thrillClickListener {
            TimeLineActivity.startActivity(requireContext())

        }



    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageSimple(t: XXLEvent) {

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }





    fun initdata(){

        HviewModel.getDBHabit()

        HviewModel.habitData.observe(this.viewLifecycleOwner) { list ->

            Hadapter.data.clear()
            Hadapter.setList(list)
            Hadapter.notifyDataSetChanged()
        }

    }



}
